package com.shawn.baseappbygroovydsl.ui.adapter

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import kotlin.properties.Delegates
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseQuickAdapter
import com.choryan.quan.videowzproject.extension.ExtensionView.show
import com.shawn.baseappbygroovydsl.R
import com.shawn.baseappbygroovydsl.bean.BeanSearchHot
import com.shawn.baseappbygroovydsl.bean.BeanWechat50
import com.shawn.baseappbygroovydsl.databinding.AdapterHotListBinding
import com.shawn.baseappbygroovydsl.databinding.ItemWechat50Binding
import com.shawn.baseappbygroovydsl.ui.view.cash.UtilAnime
import com.shawn.baseappbygroovydsl.utils.ExtensionCommon.dp

class AdapterWechat50(
) : BaseQuickAdapter<BeanWechat50, AdapterWechat50.VH>() {
    var animationCompleteListener: AnimationCompleteListener? = null

    class VH(
        parent: ViewGroup,
        val binding: ItemWechat50Binding = ItemWechat50Binding.inflate(
            LayoutInflater.from(parent.context), parent, false
        ),
    ) : RecyclerView.ViewHolder(binding.root)

    var selPos by Delegates.observable(0, onChange = { _, old, new ->
        if (old != new) {
            notifyDataSetChanged()
        }
    })

    private fun changerItemView(
        bind: ItemWechat50Binding,
        item: BeanWechat50,
        isStart: Boolean = false
    ) {
        if (item.isStepDone) {
            bind.line1.setBackgroundColor(Color.parseColor("#2FCB6B"))
            bind.line2.setBackgroundColor(Color.parseColor("#2FCB6B"))
            if (item.isDone) {
                bind.img.clearAnimation()
                bind.img.setImageResource(R.drawable.ic_wechat_50_9)
            } else {
                if (isStart) {
                    startRotation(bind.img)
                }
                bind.img.setImageResource(R.drawable.ic_wechat_50_10)
            }
        } else {
            bind.img.setImageResource(R.drawable.ic_wechat_50_12)
            bind.line1.setBackgroundColor(Color.parseColor("#999999"))
            bind.line2.setBackgroundColor(Color.parseColor("#999999"))
        }
    }

    interface AnimationCompleteListener {
        fun onAllAnimationsComplete()
    }

    private fun next(position: Int, itemCount: Int, view: View) {
        val nextPosition = position + 1
        if (nextPosition < itemCount) {
            val bean = items[nextPosition].copy(isShowAnime = true)
            view.post {
                set(nextPosition, bean)
            }
        }
        if (nextPosition == itemCount - 1) {
            animationCompleteListener?.onAllAnimationsComplete()
        }
    }

    fun startAnime() {
        val bean = items[0].copy(isShowAnime = true)
        set(0, bean)
    }


    fun animateLineView(view: View, callback: (() -> Unit)? = null) {
        view.visibility = View.INVISIBLE
        view.scaleY = 0f
        view.alpha = 0f
        val scaleAnimator = ObjectAnimator.ofFloat(view, "scaleY", 0f, 1f)
        scaleAnimator.duration = 100
        val alphaAnimator = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f)
        alphaAnimator.duration = 100
        val translateAnimator =
            ObjectAnimator.ofFloat(view, "translationY", -view.height.toFloat(), 0f)
        translateAnimator.duration = 100
        val animatorSet = AnimatorSet().apply {
            playTogether(scaleAnimator, alphaAnimator, translateAnimator)
        }
        animatorSet.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                view.visibility = View.VISIBLE
            }

            override fun onAnimationEnd(animation: Animator) {
                callback?.invoke()
            }

            override fun onAnimationCancel(animation: Animator) {
            }

            override fun onAnimationRepeat(animation: Animator) {
            }
        })
        animatorSet.start()
    }

    fun animateViewsFromLeft(
        vararg views: View,
        duration: Long,
        sequentially: Boolean = true,
        callback: (() -> Unit)? = null
    ) {
        val animators = mutableListOf<Animator>()
        for (view in views) {
            view.visibility = View.VISIBLE
            view.pivotX = 0f
            view.pivotY = view.height / 2f
            view.scaleX = 0f
            val scaleAnimator = ObjectAnimator.ofFloat(view, "scaleX", 0f, 1f)
            scaleAnimator.duration = duration
            animators.add(scaleAnimator)
        }
        val finalAnimatorSet = AnimatorSet()
        if (sequentially) {
            finalAnimatorSet.playSequentially(animators)
        } else {
            finalAnimatorSet.playTogether(animators)
        }
        finalAnimatorSet.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
            }

            override fun onAnimationEnd(animation: Animator) {
                callback?.invoke()
            }

            override fun onAnimationCancel(animation: Animator) {
            }

            override fun onAnimationRepeat(animation: Animator) {
            }
        })
        finalAnimatorSet.start()
    }

    private fun startRotation(view: View) {
        val rotateAnimation = RotateAnimation(
            0f, 360f, // 从0度旋转到360度
            Animation.RELATIVE_TO_SELF, 0.5f, // 旋转中心X（相对于自身宽度的50%）
            Animation.RELATIVE_TO_SELF, 0.5f  // 旋转中心Y（相对于自身高度的50%）
        ).apply {
            duration = 2000L // 设置动画持续时间（毫秒）
            repeatCount = Animation.INFINITE // 设置无限循环
            interpolator = LinearInterpolator() // 设置线性插值器
            fillAfter = true // 动画结束后保持最后状态
        }
        view.startAnimation(rotateAnimation)
    }

    override fun onBindViewHolder(holder: VH, position: Int, item: BeanWechat50?) {
        if (item == null) {
            return
        }
        val bind = holder.binding
        bind.tx2.setTextColor(item.te2Color.toColorInt())
        bind.tx2.text = item.tx2
        val position = holder.adapterPosition
        val itemCount = getItemCount()
        if (item.spanStr.isNotEmpty()) {
            val partsIndexStart = item.tx1.indexOf(item.spanStr)
            val spannableString = SpannableString(item.tx1)
            spannableString.setSpan(
                ForegroundColorSpan(item.te1Color.toColorInt()),
                0,
                item.tx1.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                ForegroundColorSpan(item.spanColor.toColorInt()),
                partsIndexStart,
                partsIndexStart + item.spanStr.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            bind.tx1.text = spannableString
        } else {
            bind.tx1.setTextColor(item.te1Color.toColorInt())
            bind.tx1.text = item.tx1
        }

        if (item.isShowAnime) {
            if (position == 0) {
                bind.img.show()
                UtilAnime.animateViewRotation(bind.img) {
                    bind.img.setImageResource(R.drawable.ic_wechat_50_9)
                    animateViewsFromLeft(bind.tx1, bind.tx2, duration = 200, sequentially = false) {
                        animateLineView(bind.line2) {
                            next(position, itemCount, holder.itemView)
                        }
                    }
                }
            } else if (position == itemCount - 1) {
//                bind.line1.show()
                animateLineView(bind.line1) {
                    bind.img.show()
                    UtilAnime.animateViewRotation(bind.img) {
                        changerItemView(bind, item, true)
                        if (itemCount == 2) {
                            bind.tx1.setBackgroundResource(R.drawable.shape_ff9800_ff4f2d_6)
                            bind.tx1.setPadding(
                                5f.dp.toInt(),
                                2f.dp.toInt(),
                                5f.dp.toInt(),
                                2f.dp.toInt()
                            )
                        } else {
                            bind.tx1.background = null
                            bind.tx1.setPadding(0, 0, 0, 0)
                        }
                        animateViewsFromLeft(bind.tx1, duration = 200, sequentially = false) {
                            next(position, itemCount, holder.itemView)
                        }
                    }
                }
            } else {
//                bind.line1.show()
                animateLineView(bind.line1) {
                    bind.img.show()
                    UtilAnime.animateViewRotation(bind.img) {
                        changerItemView(bind, item, true)
                        animateViewsFromLeft(
                            bind.tx1,
                            bind.tx2,
                            duration = 200,
                            sequentially = false
                        ) {
                            animateLineView(bind.line2) {
                                next(position, itemCount, holder.itemView)
                            }
                        }
                    }
                }
            }
        }
    }

    override fun onBindViewHolder(
        holder: VH,
        position: Int,
        item: BeanWechat50?,
        payloads: List<Any>
    ) {
        super.onBindViewHolder(holder, position, item, payloads)
        if (item == null) {
            return
        }
        val bind = holder.binding
        if (item.spanStr.isNotEmpty()) {
            val partsIndexStart = item.tx1.indexOf(item.spanStr)
            val spannableString = SpannableString(item.tx1)
            spannableString.setSpan(
                ForegroundColorSpan(item.te1Color.toColorInt()),
                0,
                item.tx1.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                ForegroundColorSpan(item.spanColor.toColorInt()),
                partsIndexStart,
                partsIndexStart + item.spanStr.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            bind.tx1.text = spannableString
        } else {
            bind.tx1.setTextColor(item.te1Color.toColorInt())
            bind.tx1.text = item.tx1
            bind.img.clearAnimation()
            bind.img.setImageResource(R.drawable.ic_wechat_50_9)
            bind.line1.setBackgroundColor(Color.parseColor("#2FCB6B"))
            bind.line2.setBackgroundColor(Color.parseColor("#2FCB6B"))
        }
    }

    override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
        return VH(parent)
    }

}